package com.yu.blog.utils.SMSUtil;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.OpenApiRequest;
import com.aliyun.teaopenapi.models.Params;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.internal.LinkedTreeMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SendSms {

    private static String accessKeyId;
    @Value("${SMS.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        SendSms.accessKeyId = accessKeyId;
    }
    private static String accessKeySecret;
    @Value("${SMS.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        SendSms.accessKeySecret = accessKeySecret;
    }

    public static boolean sendSMS(String phoneNum,String randomCode) throws Exception {
        Client client = SendSms.createClient();
        Params params = SendSms.createApiInfo();
        // query params
        Map<String, Object> queries = new HashMap<>();
        queries.put("PhoneNumbers", phoneNum);
        queries.put("SignName", "余珍安的个人博客");
        queries.put("TemplateCode", "SMS_460950251");
        queries.put("TemplateParam", "{\"code\":\""+randomCode+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        OpenApiRequest request = new OpenApiRequest()
                .setQuery(com.aliyun.openapiutil.Client.query(queries));
        // 复制代码运行请自行打印 API 的返回值
        // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        Map<String, ?> obj=client.callApi(params, request, runtime);
        Integer code=Integer.parseInt(obj.get("statusCode").toString());
        if(code.equals(200)) {
            LinkedTreeMap<String, Object> map = (LinkedTreeMap<String, Object>) obj.get("body");
            return "OK".equals(map.get("Message"));
        }
        return false;



    }

    public static Client createClient() throws Exception {
        Config config = new Config()
                // AccessKey ID
                .setAccessKeyId(accessKeyId)
                // AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static Params createApiInfo(){
        return new Params()
                // 接口名称
                .setAction("SendSms")
                // 接口版本
                .setVersion("2017-05-25")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("RPC")
                // 接口 PATH
                .setPathname("/")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
    }
}
